package JavaDesign.report_4.t_2;

import java.util.ArrayList;

/**
 * @author zouran
 * createDate：2023/10/18  9:30
 */
interface Investor {
    public void response(Stock stock);
}

class Stock {
    private ArrayList<Investor> investors;
    private String stockName;
    private double price;

    public Stock(String stockName, double price) {
        this.stockName = stockName;
        this.price = price;
        investors = new ArrayList<Investor>();
    }

    public void attach(Investor investor) {
        investors.add(investor);
    }

    public void detach(Investor investor) {
        investors.remove(investor);
    }

    public String getStockName() {
        return this.stockName;
    }

    public void setStockName(String stockName) {
        this.stockName = stockName;
    }

    public double getPrice() {
        return this.price;
    }

    public void setPrice(double price) {
        double range = Math.abs(price - this.price) / this.price;
        this.price = price;
        if (range >= 0.05) {
            this.notifyInvestor();
        }
    }

    public void notifyInvestor() {
        for (Object obj : investors) {
            ((Investor) obj).response(this);
        }
    }
}

class ConcreteInvestor implements Investor {
    private String name;

    public ConcreteInvestor(String name) {
        this.name = name;
    }

    public void response(Stock stock) {
        System.out.print("Investor name :" + name);
        System.out.print("------Stock name:" + stock.getStockName());
        System.out.print("涨跌幅超过5%------");
        System.out.println("当前价格:" + stock.getPrice());
    }
}

class Client {
    public static void main(String args[]) {
        Investor investor1, investor2;
        investor1 = new ConcreteInvestor("小王");
        investor2 = new ConcreteInvestor("小李");

        Stock haier = new Stock("haier", 20.00);
        haier.attach(investor1);
        haier.attach(investor2);

        haier.setPrice(25.00);
    }
}

